import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, getRefreshToken, setRefreshToken, clearAllCache } from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
	  refreshToken: getRefreshToken(),
    name: '',
    roles: [],
    userId: ''
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_ID: (state, id) => {
      state.userId = id
    }
  },
  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.password, userInfo.identificationCode).then(response => {
          const data = response.data
          if (+response.code === 0) {
            setToken(data.access_token)
            commit('SET_TOKEN', data.access_token)
            setRefreshToken(data.refresh_token)
            resolve('登录成功')
          } else {
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const data = response.data
          /*if (data.roleIds && data.roleIds.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', data.roleIds)
          } else {
            reject('身份认证失败，请尝试重新登录或者联系管理员')
          }*/
          if (data && data.id) {
            commit('SET_NAME', data.realName)
            commit('SET_ID', data.id)
          } else {
            reject('身份认证失败，请尝试重新登录或者联系管理员')
          }
          resolve(response)
        }).catch(error => {
          // reject(error)
          resolve(error)  // 特殊情况：因网络等问题拉取用户失败的，不做认证失败处理
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_NAME', '')
          commit('SET_ID', '')
          clearAllCache()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_NAME', '')
        commit('SET_ID', '')
        clearAllCache()
        resolve()
      })
    }
  }
}

export default user
